import React, { useState, useEffect } from 'react'
import { Layout, Dropdown, Avatar, Menu, Modal, message, Form, Input } from 'antd'
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined
} from '@ant-design/icons'
import { useNavigate } from 'react-router'
import axios from 'axios'
import base from '../routes/baseUrl'
const { Header } = Layout

export default function TopHeader(props) {

  const [collapsed, setCollapsed] = useState(false) // 侧边栏折叠按钮
  const [isModalVisible, setIsModalVisible] = useState(false) // 修改密码模态框
  const { id, name, userType, password, changePassword } = JSON.parse(sessionStorage.getItem('token'))
  const navigate = useNavigate()
  const [form] = Form.useForm()

  useEffect(() => {
    // console.log(JSON.parse(sessionStorage.getItem('token')))
  }, [])

  const handleOk = (value) => { // 修改密码模态框确定的回调
    // console.log(value)
    // message.success('修改成功')
    form.validateFields().then(values => {
      const {passwordOld, passwordNew, passwordConfirm} = values
      if (passwordOld !== password) {
        message.error('旧密码错误！')
      } else {
        if (passwordNew !== passwordConfirm) {
          message.error('两次输入的新密码不一致！')
        } else {
          if (passwordNew === passwordOld) {
            message.error('新密码不能与旧密码相同！')
          } else {
            axios.patch(base + `/${userType === 1 ? 'student' : 'teacher'}s/${id}`, {password: passwordNew}).then(res => {
              sessionStorage.setItem('token', JSON.stringify({...res.data, changePassword}))
              message.success('修改成功')
              setIsModalVisible(false)
              form.resetFields()
            }).catch(reason => {
              console.log('修改发生错误', reason)
              message.error('修改发生错误')
            })
          }
        }
      }
    }).catch(info => {
      console.log('发生错误', info)
    })
  }

  const menu = (
    <Menu
      items={
        [
          {
            key: '1',
            label: '修改密码',
            onClick: () => {
              setIsModalVisible(true)
            }
          },
          {
            key: '2',
            danger: true,
            label: '退出登录',
            onClick: () => {
              sessionStorage.removeItem('token')
              props.setIsLogin(false)
              navigate('/login')
            }
          },
        ]}
    />
  )

  return (
    <div>
      <Header
        className="site-layout-background"
        style={{
          padding: '0 18px',
        }}
      >
        {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
          className: 'trigger',
          onClick: () => {
            setCollapsed(!collapsed)
            props.setMenuCollapsed(!collapsed)
          },
        })}
        <div style={{ float: 'right' }}>
          <span>欢迎！<b style={{ color: '#007457' }}>{name}</b>{userType === 1 ? '同学' : '老师'}&nbsp;&nbsp;</span>
          <Dropdown overlay={menu}>
            <Avatar size='large' icon={<UserOutlined />} />
          </Dropdown>
        </div>
      </Header>
      <Modal
        title='修改密码'
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={() => {
          console.log('操作取消')
          setIsModalVisible(false)
        }}
        okText='修改'
        cancelText='取消'
      >
        <Form
          name="修改密码"
          form={form}
          layout='vertical'
          initialValues={{
            remember: true,
          }}
          // onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="旧密码"
            name="passwordOld"
            rules={[
              {
                required: true,
                message: '请输入旧密码！',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="passwordNew"
            rules={[
              {
                required: true,
                message: '请输入新密码！',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="passwordConfirm"
            rules={[
              {
                required: true,
                message: '请再次输入新密码！',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
